<!--
2019-05-10 前端hash路由原理2

2.通过页面的无刷新，仅改变页面的 hash 值，而达到页面内容的变更
2.1 构造一个路由函数
2.2 对路由的hash值进行监听，如果hash 发生改变，则执行加载函数
2.3 定义路由配置规则
2.4 对路由进行初始化即调用 
-->

<!DOCTYPE html>
<html lang='en'>
<head>
  <meta charset="UTF-8" />
  <title>hash路由</title>
  <style type="text/css">
    html, body{
      margin: 0;
      padding: 0;
    }
    header{
      widows: 100%;
      height: 48px;
      background-color: #000;
      color: #fff;
      display: flex;
      align-items: center;
      padding: 0 100px;
    }
    nav{
      list-style-type: none;
      padding-left: 10px;
      float: left;
      width: 20%;
      height:30em;
    }
    section{
      width: 80%;
    }
    .clear{
      clear: both;
    }
    footer{
      width: 100%;
      height:48px;
      background: #cba;
      position: fixed;
      bottom: 0;
    }
  </style>
  <script type="text/javascript">
    (function(){
      var Router=function(options){
        var options=Object.assign({}, Router.Defaults, options);
        this.el=options.el;
        this.routes={};
        this.currenturl='/';
        this.init(options.routes);
      };
      
      Router.Defaults={
        el: null,
        routes: []
      }
      //监听路由的hash值
      Router.prototype.init=function(arr_routes){
        var that=this;
        arr_routes.forEach(function(data, indx){
          if(data.path in that.routes){

          }else
            that.routes[data.path]=data.template;
        });

        this.reloadpage();
        window.addEventListener('hashchange', this.reloadpage.bind(this));
      };
      
      
      Router.prototype.reloadpage=function(){
        this.currenturl=location.hash.substring(1)||'/';
        var el_node = document.querySelector(this.el)
        if(el_node){
          el_node.innerHTML=this.routes[this.currenturl];
        }
      };

      Router.prototype.adapterurl=function(){
      };
      window.Router=Router;
    })();

    window.onload=function(){
      var userRoutes=[
        {
          path: '/',
          template: '<div>你是homepage</div>'
        },
        {
          path: '/01',
          template: '<div>页面1内容：一只小小小鸟</div>'
        },
        {
          path: '/02',
          template: '<div>个人基本信息页面</div>'
        },
      ]

      var Crouter = new Router({
        el: '#content',
        routes: userRoutes
      });
    }
  </script>
</head>
<body>
  <header>这里是头部</header>
  <nav>
    <li><a href="#/">home page</a></li>
    <li><a href="#/01">页面1</a></li>
    <li><a href="#/02">页面1</a></li>
    <li><a href="#/03">页面2</a></li>
  </nav>
  <section id="content"></section>
  <div class="clear"></div>
  <footer>页脚</footer>
</body>
</html>

